package com.appspot.smartgan.adapter;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.appspot.smartgan.ChildActivity;
import com.appspot.smartgan.R;
import com.appspot.smartgan.util.Message;

public class MessagesAdapter extends ArrayAdapter<Message> {

	private final List<Message> messages;
	private final Context context;
	private final LayoutInflater inflater;
	
	public MessagesAdapter(Context context, List<Message> messages) {
		super(context, R.layout.message_board_row, messages);
		
		this.inflater = LayoutInflater.from(context);
		this.context = context;
		if (messages == null) {
			this.messages = new LinkedList<Message>();
		} else {
			this.messages = messages;
		}
	}
	
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		Message message = messages.get(position);
		ViewHolder holder;
		
		if (convertView == null) {
			if (message.isToTeacher()) {
				Log.d("SMARTGAN", "message sent by teacher");
				convertView = inflater.inflate(R.layout.sent_message_row, null);
				holder = new ViewHolder(convertView,
						R.id.sentMessageTitleTextView, 
						R.id.sentMessageMessageTextView);
				convertView.setTag(holder);
			} else {
				if (message.getImageUrl() == null) {
					convertView = inflater.inflate(R.layout.message_board_row, null);
					holder = new ViewHolder(convertView,
							R.id.messageBoardTitleTextView, 
							R.id.messageBoardMessageTextView);
					convertView.setTag(holder);
				} else {
					convertView = inflater.inflate(R.layout.message_with_image_row, 
							null);
					holder = new ViewHolder(convertView,
							R.id.messageWithImageTitleTextView,
							R.id.messageWithImageMessageTextView,
							R.id.message_with_image_image_view);
					convertView.setTag(holder);
				}
			}
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		holder.title.setText(message.getTitle());
		holder.message.setText(message.getMessage());
		
		// display image in image view which is also not null
		if (message.getImageBitmap() != null) {
			holder.image.setImageBitmap(message.getImageBitmap());
		} else {
			if (message.getImageUrl() != null) {
				GetXmlTask task = new GetXmlTask(holder, message);
				task.execute(new String[] {message.getImageUrl()});
			}
		}
		
		convertView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ChildActivity activity = (ChildActivity) context;
				activity.displayMessage(messages.get(position));
			}
		});
		
		convertView.setBackgroundResource(R.drawable.shape_message);
		
		return convertView;
	}
	
	
	//-------------------------------------------------------------------------
	
	private class GetXmlTask extends AsyncTask<String, Void, Bitmap> {
		
		private ViewHolder holder;
		private Message message;
		
		public GetXmlTask(ViewHolder holder, Message message) {
			this.holder = holder;
			this.message = message;
		}
		
		@Override
		protected Bitmap doInBackground(String... urls) {
			Bitmap bitmap = downloadImage(urls[0]);
			return bitmap;
		}
		
		@Override
		protected void onPostExecute(Bitmap result) {
			holder.image.setImageBitmap(result);
			message.setImageBitmap(result);
		}

		// Creates Bitmap from InputStream and returns it
		private Bitmap downloadImage(String url) {
			Log.d("SMARTGAN", "downloading image");
			Bitmap bitmap = null;
			InputStream stream = null;
			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inSampleSize = 1;

			try {
				stream = getHttpConnection(url);
				bitmap = BitmapFactory.
						decodeStream(stream, null, bmOptions);
				stream.close();
			} catch (IOException e) {
				Log.e("SMARTGAN", "Error: " + e.getMessage());
			}
			
			Log.d("SMARTGAN", "image downloaded");
			return bitmap;
		}
		
		// Makes HttpURLConnection and returns InputStream
		private InputStream getHttpConnection(String urlString)
				throws IOException {
			InputStream stream = null;
			URL url = new URL(urlString);
			URLConnection connection = url.openConnection();

			try {
				HttpURLConnection httpConnection = (HttpURLConnection) connection;
				httpConnection.setRequestMethod("GET");
				httpConnection.connect();

				if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
					stream = httpConnection.getInputStream();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return stream;
		}
	}
	
	
	//-------------------------------------------------------------------------
	
	// static holder class
	static class ViewHolder {
		TextView title;
		TextView message;
		ImageView image;
		
		ViewHolder(View view, int titleId, int messageId) {
			title = (TextView) view.findViewById(titleId);
			message = (TextView) view.findViewById(messageId);
			
			image = null;
		}
		
		ViewHolder(View view, int titleId, int messageId, int imageId) {
			title = (TextView) view.findViewById(titleId);
			message = (TextView) view.findViewById(messageId);
			image = (ImageView) view.findViewById(imageId);
		}
	}
	
}
